<?php
/**
 * Created by PhpStorm.
 * Author: yangyang
 * Date: 2016/11/29
 * Time: 14:44
 */

namespace Icsoc\CoreBundle\Common;

use \MongoDB;
use MongoDB\Client;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 封装mongodb的公用方法
 *
 * Class MongoDBCommon
 *
 * @package Icsoc\CoreBundle\Common
 */
class MongoDBCommon
{

    public $mongoConn;
    public $config;
    public $dataConn;

    /**
     * Common constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->config = $this->container->getParameter("mongodb");
        $this->mongoConn = new Client($this->config['uri']);
        $this->dataConn = $this->mongoConn->selectDatabase(
            $this->config['database']
        );
    }

    /**
     * 获取数据的总个数
     *
     * @param  array  $condition //查询条件
     * @param  string $column    //集合(表)
     * @return integer $count    //数据条数
     */
    public function getTotalNum($condition, $column)
    {
        $collection = $this->dataConn->selectCollection($column);
        $count = $collection->count($condition);

        return $count;
    }

    /**
     * 根据条件从mongodb中获取图形报表的数据
     *
     * @param $condition
     * @param $column
     * @return MongoDB\Driver\Cursor
     */
    public function getDataForCharts($condition, $column)
    {
        $collection  = $this->dataConn->selectCollection($column);
        $data = $collection->aggregate($condition);

        return $data;
    }

    /**
     * 获取满足条件的数据
     *
     * @param  array  $param  //查询条件
     * @param  string $column //集合(表)
     * @return mixed $data
     */
    public function getDataForPage($param, $column)
    {
        $allIds = $param['allIds'];
        $collection = $this->dataConn->selectCollection($column);
        $condition = array('_id' => array('$in' => $allIds));
        $data = $collection->find($condition);

        return $data;
    }

    /**
     * 复杂的取出mongodb数据
     * @param  array  $param  //查询条件
     * @param  string $column //集合(表)
     * @param  array  $expert //排序
     * @return MongoDB\Driver\Cursor
     */
    public function otherGetDataForPage($param, $column, $expert = array())
    {
        $collection = $this->dataConn->selectCollection($column);
        $data = $collection->find($param, $expert);

        return $data;
    }

    /**
     * 获取ivr轨迹
     *
     * @param  array  $param  //查询条件
     * @param  string $column //集合(表)
     * @return mixed $data
     */
    public function getDataIvr($param, $column)
    {
        $callId = $param['call_id'];
        $collection = $this->dataConn->selectCollection($column);
        $condition = array('call_id' =>(int) $callId);
        $data = $collection->find($condition);
        $ivr = array();
        foreach ($data as $restaurant) {
            $ivr = $restaurant;
        };

        return $ivr;
    }
}